﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Tiens.NotificationHub.Core.Extensions
{
    public static class HttpContentExtensions
    {

        public static async Task<TEntity> ReadAsAsync<TEntity>(this HttpContent httpContent)
        {
            var data = await httpContent.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TEntity>(data);
        }

        public static async Task<bool> TryReadAs<TEntity>(this HttpContent httpContent, TEntity entity)
            where TEntity : class
        {
            var success = true;
            try
            {
                entity = await httpContent.ReadAsAsync<TEntity>();
            }
            catch (Exception e)
            {
                success = false;
            }

            return success;
        }
    }
}
